/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Controller.ClientFTP;
import Controller.ConnReader;
import Controller.Connection;
import Controller.Controller;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import org.apache.commons.net.ftp.FTPFile;

/**
 *
 * @author nexo__000
 */
public class Vista extends JFrame implements ActionListener, MouseListener {

    private JScrollPane jspLog;
    private JScrollPane jspRemoteTree;
    private JScrollPane jspLocalTree;
    private JScrollPane jspLocalFiles;
    private JScrollPane jspRemoteFiles;
    private JButton jbConnect;
    private JButton jbDownload;
    private JButton jbEditConnection;
    private JButton jbLocalChangeDir;
    private JButton jbUpload;
    private JComboBox jcbConnections;
    private JComboBox jcbLocalDir;
    private JComboBox jcbRemoteDir;
    private JList jlLocalFiles;
    private JButton jbLocalReload;
    private JButton jbLocalUp;
    private JButton jbRemoteChangeDir;
    private JList jlRemoteFiles;
    private JButton jbRemoteReload;
    private JButton jbRemoteUp;
    private JTree jtLocalTree;
    private JTree jtRemoteTree;
    private JTextArea jtaLog;
    private WindowAdapter windowAdapter = null;

    private JButton jbLocalNewDir;
    private JButton jbRemoteNewDir;
    private JButton jbLocalRename;
    private JButton jbRemoteRename;
    private JButton jbLocalDelete;
    private JButton jbRemoteDelete;

    // Objetos
    ClientFTP client = Controller.getClient();

    /**
     * Creates new form Vista2
     */
    public Vista() {
        initComponents();
        setLookAndFeel();
        myInitComponents();
//        populateLocalJTree();
//        populateRemoteJTree();
        setButtonsFunctions();
        loadComboConnections();
    }

    public void print(String in) {
        System.out.println(in);
        jtaLog.append("\n" + in);
    }

    public void reloadVista() {
        client = Controller.getClient();
        populateLocalJTree();
        populateRemoteJTree();
    }

    public void populateLocalJTree() {
//        localModel = new FileTreeModel(client.getLocalDir());
//        jtLocalTree.setModel(localModel);
        File raiz = client.getLocalDir();
        DefaultMutableTreeNode padre = new DefaultMutableTreeNode(raiz, true);
        DefaultTreeModel modelo = new DefaultTreeModel(padre, true);
        jtLocalTree.setModel(modelo);
        //modelo.setRoot((TreeNode) padre);
        int index = 0;
        for (File archivin : raiz.listFiles()) {
            if (archivin.isDirectory()) {
                DefaultMutableTreeNode hijo = new DefaultMutableTreeNode(archivin.getName(), true);
                modelo.insertNodeInto(hijo, padre, index++);
            } else if (archivin.isFile()) {
                DefaultMutableTreeNode hijo = new DefaultMutableTreeNode(archivin.getName(), false);
                modelo.insertNodeInto(hijo, padre, index);
            }
        }
    }

    public void populateRemoteJTree() {
        //ArrayList<DefaultMutableTreeNode> hijos = new ArrayList();
        String raiz = client.getWorkingDir();
        DefaultMutableTreeNode padre = new DefaultMutableTreeNode(raiz, true);
        DefaultTreeModel modelo = new DefaultTreeModel(padre, true);
        jtRemoteTree.setModel(modelo);
        //modelo.setRoot((TreeNode) padre);
        int index = 0;
        for (FTPFile archivin : client.getChildren(raiz)) {
            if (archivin.isDirectory()) {
                DefaultMutableTreeNode hijo = new DefaultMutableTreeNode(archivin.getName(), true);
                modelo.insertNodeInto(hijo, padre, index++);
            } else if (archivin.isFile()) {
                DefaultMutableTreeNode hijo = new DefaultMutableTreeNode(archivin.getName(), false);
                modelo.insertNodeInto(hijo, padre, index++);
            }
        }
    }

    public void setLookAndFeel() {
        try {
            // Set cross-platform Java L&F (also called "Metal")
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Vista.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Vista.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Vista.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Vista.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }

    public ImageIcon prepareIcon(String in, int width, int height) {
        ImageIcon icon = new ImageIcon(in);
        Image img = icon.getImage();
        Image newImg = img.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
        return new ImageIcon(newImg);
    }

    public void setButtonsFunctions() {
        jbUpload.addActionListener(this);
        jbDownload.addActionListener(this);
    }

    public void upload() {
        switch (jtLocalTree.getSelectionCount()) {
            case 2:
                break;
            case 1:
                client.upload(jtLocalTree.getLastSelectedPathComponent().toString(), jtLocalTree.getLastSelectedPathComponent().toString());
                break;
            case 0:
                break;
        }
    }

    public void download() {
        switch (jtRemoteTree.getSelectionCount()) {
            case 1:
                System.out.println(jtRemoteTree.getLastSelectedPathComponent().toString());
                client.download(jtRemoteTree.getLastSelectedPathComponent().toString(), jtRemoteTree.getLastSelectedPathComponent().toString());
                break;
            case 0:
                break;
        }
    }

    public void myInitComponents() {
        setLocationRelativeTo(null);
        setTitle("DamFTP");
        getContentPane().setLayout(null);
        setSize(800, 600);
        //inicializar todos los componentes
        jspRemoteTree = new JScrollPane();
        jtRemoteTree = new JTree();
        jtRemoteTree.setModel(null);

        //añadir el modelo
        jspLocalTree = new JScrollPane();
        jtLocalTree = new JTree();
        jtLocalTree.setModel(null);

        //Añadimos los eventos de ratón
        jtRemoteTree.addMouseListener(this);
        jtLocalTree.addMouseListener(this);

        //añadir el modelo
        jspLocalFiles = new JScrollPane();
        jlLocalFiles = new JList();
        jspRemoteFiles = new JScrollPane();
        jlRemoteFiles = new JList();

        jbUpload = new JButton();
        jbDownload = new JButton();
        jbLocalUp = new JButton();
        jcbLocalDir = new JComboBox();
        jbLocalChangeDir = new JButton();
        jbLocalReload = new JButton();
        jbRemoteUp = new JButton();
        jbRemoteReload = new JButton();
        jcbRemoteDir = new JComboBox();
        jbRemoteChangeDir = new JButton();
        jbConnect = new JButton();
        jbEditConnection = new JButton();

        jbLocalNewDir = new JButton();
        jbLocalRename = new JButton();
        jbRemoteNewDir = new JButton();
        jbRemoteRename = new JButton();
        jbLocalDelete = new JButton();
        jbRemoteDelete = new JButton();

        jcbConnections = new JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("jfFTP"); // NOI18N
        setResizable(false);

        jspRemoteTree.setViewportView(jtRemoteTree);

        jspLocalTree.setViewportView(jtLocalTree);

        jlLocalFiles.setName(""); // NOI18N
        jspLocalFiles.setViewportView(jlLocalFiles);

        jlRemoteFiles.setName(""); // NOI18N
        jspRemoteFiles.setViewportView(jlRemoteFiles);

        jcbLocalDir.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));

        jbLocalChangeDir.setText("Cambiar");
        jbLocalChangeDir.setFocusable(false);
        jbLocalChangeDir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbLocalChangeDir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jcbRemoteDir.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));

        jbRemoteChangeDir.setText("Cambiar");
        jbRemoteChangeDir.setFocusable(false);
        jbRemoteChangeDir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbRemoteChangeDir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        jbConnect.setText("Conectar");
        jbConnect.addActionListener(this);
        jbEditConnection.setText("Editar conexiones");

        jcbConnections.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));

        //AÑADIRLOS AL JFRAME
        //LINEA DEL BOTON DE CONEXION, EDICION Y CB DE CONEXIONES
        jbConnect.setBounds(20, 20, 90, 24);
        add(jbConnect);
        jbEditConnection.setBounds(120, 20, 150, 24);
        jbEditConnection.addMouseListener(this);
        add(jbEditConnection);

        jcbConnections.setBounds(280, 20, 500, 24);
        jcbConnections.addItemListener(new ItemChangeListener());
        add(jcbConnections);

        //LINEA DE BOTONES LOCALES Y REMOTOS
        //LOCALES
        jbLocalUp.setIcon(prepareIcon("img/up.png", 35, 35));
        jbLocalUp.setBounds(20, 63, 40, 40);
        jbLocalUp.addMouseListener(this);
        add(jbLocalUp);
        jbLocalReload.setText(null);
        jbLocalReload.setIcon(prepareIcon("img/reload.png", 35, 35));
        jbLocalReload.addMouseListener(this);
        jbLocalReload.setBounds(70, 63, 40, 40);
        add(jbLocalReload);
        //jcbLocalDir.setBounds(120, 71, 150, 24);
        //add(jcbLocalDir);
        jbLocalNewDir.setText(null);
        jbLocalNewDir.setIcon(prepareIcon("img/create.png", 35, 35));
        jbLocalNewDir.addMouseListener(this);
        jbLocalNewDir.setBounds(120, 63, 40, 40);
        add(jbLocalNewDir);
        jbLocalRename.setBounds(170, 63, 40, 40);
        jbLocalRename.setText(null);
        jbLocalRename.setIcon(prepareIcon("img/rename.png", 35, 35));
        jbLocalRename.addMouseListener(this);
        add(jbLocalRename);

        jbLocalDelete.setBounds(220, 63, 40, 40);
        jbLocalDelete.setText(null);
        jbLocalDelete.setIcon(prepareIcon("img/delete.png", 35, 35));
        jbLocalDelete.addMouseListener(this);
        add(jbLocalDelete);

        //jbLocalChangeDir.setBounds(280, 71, 80, 24);
        //add(jbLocalChangeDir);
        //REMOTOS
        jbRemoteUp.setIcon(prepareIcon("img/up.png", 35, 35));
        jbRemoteUp.setBounds(440, 63, 40, 40);
        jbRemoteUp.addMouseListener(this);
        add(jbRemoteUp);
        jbRemoteReload.setBounds(490, 63, 40, 40);
        jbRemoteReload.setIcon(prepareIcon("img/reload.png", 35, 35));
        jbRemoteReload.addMouseListener(this);
        add(jbRemoteReload);
        //jcbRemoteDir.setBounds(540, 71, 150, 24);
        //add(jcbRemoteDir);
        //jbRemoteChangeDir.setBounds(700, 71, 80, 24);
        //add(jbRemoteChangeDir);
        jbRemoteNewDir.setText(null);
        jbRemoteNewDir.setIcon(prepareIcon("img/create.png", 35, 35));
        jbRemoteNewDir.addMouseListener(this);
        jbRemoteNewDir.setBounds(540, 63, 40, 40);
        add(jbRemoteNewDir);
        jbRemoteRename.setBounds(590, 63, 40, 40);
        jbRemoteRename.setText(null);
        jbRemoteRename.setIcon(prepareIcon("img/rename.png", 35, 35));
        jbRemoteRename.addMouseListener(this);
        add(jbRemoteRename);

        jbRemoteDelete.setBounds(640, 63, 40, 40);
        jbRemoteDelete.setText(null);
        jbRemoteDelete.setIcon(prepareIcon("img/delete.png", 35, 35));
        jbRemoteDelete.addMouseListener(this);
        add(jbRemoteDelete);

        //LINEA DE JTREES
        jspLocalTree.setBounds(20, 113, 340, 300);
        add(jspLocalTree);
        jspRemoteTree.setBounds(440, 113, 340, 300);
        add(jspRemoteTree);

        //BOTONES DE DOWN Y UP
        //Esto es tela de cutre a ver si me da tiempo a cambiarlo.
        jbUpload.setText(null);
        jbUpload.setIcon(prepareIcon("img/upload.png", 40, 40));
        jbUpload.setBounds(377, 197, 46, 46);
        add(jbUpload);
        jbDownload.setText(null);
        jbDownload.setIcon(prepareIcon("img/download.png", 40, 40));
        jbDownload.setBounds(377, 257, 46, 46);
        add(jbDownload);
        //HUECO PARA PONER LA LISTA DE ARCHIVOS SI LO VEMOS NECESARIO
        //LINEA PARA JLOG
        jtaLog = new JTextArea();
        jspLog = new JScrollPane(jtaLog);
        jspLog.setBounds(20, 430, 760, 130);
        jtaLog.setColumns(20);
        jtaLog.setRows(5);
        jtaLog.setEnabled(true);
        jtaLog.setEditable(false);
        add(jspLog);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 800, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 600, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Vista.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Vista.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Vista.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Vista.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Vista().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    @Override
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource().equals(jbUpload)) {
            print("up");
            upload();
            reloadVista();
        } else if (ae.getSource() == jbDownload) {
            System.out.println("down");
            download();
            reloadVista();
        } else if ((ae.getSource() == jbLocalReload) || (ae.getSource() == jbRemoteReload)) {
            System.out.println("reload");
            reloadVista();
        } else if (ae.getSource() == jbConnect) {
            System.out.println("conect");
            Controller.connect();
            client = Controller.getClient();
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (SwingUtilities.isLeftMouseButton(e)) {
            if (e.getSource().equals(jbUpload)) {
                System.out.println("up");
                upload();
                reloadVista();
            }
            //System.out.println(e.getSource().toString());
            if (e.getSource().equals(jbLocalUp)) {
                client.localGoUp();
                print("lololol");
                print("El directorio local es: " + client.getLocalDirString());
                reloadVista();
            }
            if (e.getSource().equals(jbRemoteUp)) {
                client.remoteGoUp();
                print("El directorio remoto es: " + client.getWorkingDir());
                reloadVista();
            }
            if (e.getSource().equals(jtLocalTree)) {
                if (e.getClickCount() == 2) {
                    client.localGoInto(jtLocalTree.getLastSelectedPathComponent().toString());
                    print("El directorio local es: " + client.getLocalDirString());
                    reloadVista();
                }
            }
            if (e.getSource().equals(jtRemoteTree)) {
                if (e.getClickCount() == 2) {
                    client.remoteGoInto(jtRemoteTree.getLastSelectedPathComponent().toString());
                    print("El directorio remoto es: " + client.getWorkingDir());
                    reloadVista();
                }
            }
            if (e.getSource().equals(jbEditConnection)) {
                EditorConex ec = new EditorConex();
                ec.setVisible(true);
            }
            if (e.getSource().equals(jbLocalReload)) {
                populateLocalJTree();
            }
            if (e.getSource().equals(jbRemoteReload)) {
                populateRemoteJTree();
            }
            if (e.getSource().equals(jbLocalNewDir)) {
                String newDir;
                newDir = popUpWindow("Introduce el nombre del directorio");
                if (!newDir.equals(null)) {
                    client.createLocalDir(newDir);
                    populateLocalJTree();
                }
            }
            if (e.getSource().equals(jbLocalRename)) {
                String newDir;
                newDir = popUpWindow("Renombrando el directorio como");
                if (!newDir.equals(null)) {
                    client.renameLocalDir(jtLocalTree.getLastSelectedPathComponent().toString(), newDir);
                    populateLocalJTree();
                }
            }
            if (e.getSource().equals(jbRemoteNewDir)) {
                String newDir;
                newDir = popUpWindow("Introduce el nombre del directorio");
                if (!newDir.equals(null)) {
                    client.createRemoteDir(newDir);
                    populateRemoteJTree();
                }
            }
            if (e.getSource().equals(jbRemoteRename)) {
                String newDir;
                newDir = popUpWindow("Renombrando el directorio como");
                if (!newDir.equals(null)) {
                    client.renameRemoteDir(jtRemoteTree.getLastSelectedPathComponent().toString(), newDir);
                    populateRemoteJTree();
                }
            }
            if (e.getSource().equals(jbLocalDelete)) {
                client.deleteLocalFile(jtLocalTree.getLastSelectedPathComponent().toString());
                populateLocalJTree();
            }
            if (e.getSource().equals(jbRemoteDelete)) {
                client.deleteRemoteFile(jtRemoteTree.getLastSelectedPathComponent().toString());
                populateRemoteJTree();
            }
        }
        if (SwingUtilities.isRightMouseButton(e)) {
            //System.out.println("right click");
        }
    }

    @Override
    public void mousePressed(MouseEvent e
    ) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mouseReleased(MouseEvent e
    ) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mouseEntered(MouseEvent e
    ) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mouseExited(MouseEvent e
    ) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void loadComboConnections() {
        ConnReader cr = new ConnReader();
        jcbConnections.setModel(new DefaultComboBoxModel(cr.getNames()));
        setConnection();
    }

    public void setConnection() {
        ConnReader cr = new ConnReader();
        int index = cr.find((String) jcbConnections.getSelectedItem());
        Connection con = cr.get(index);
        Controller.setParameters(con.getHost(), con.getUser(), con.getPass());
    }

    public void setConnection(String conName) {
        ConnReader cr = new ConnReader();
        int index = cr.find(conName);
        Connection con = cr.get(index);
        Controller.setParameters(con.getHost(), con.getUser(), con.getPass());
    }

    void selectComboItem(String conn) {
        jcbConnections.setSelectedItem(conn);
    }

    class ItemChangeListener implements ItemListener {

        @Override
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                setConnection();
            }
        }
    }

    public static String popUpWindow(String text) {
        return JOptionPane.showInputDialog(text + ": ");
    }
}
